import React, { useReducer } from 'react'
export const initState = {
  name: 'xia',
  age: 18
}
const reducer = (state, action) => {
  const {type, payload} = action
  switch (type) {
    case 'increment':
      return {...state, age: state.age + 1}
    case 'decrement':
      return {...state, age: state.age - 1}
    case 'changePerson':
      return {...state,...payload}
    default:
      return state
  }
}

export default function ReducerDemo() {
  const [state, dispatch] = useReducer(reducer, initState)
  const {name, age} = state
  return (
    <div>
      <h2>useReducer的用法</h2>
      <h4>姓名:{name}, 年龄:{age}</h4>
      <button onClick={() => dispatch({type:'increment'})}>增加年龄</button>
      <button onClick={() => dispatch({type:'decrement'})}>减小年龄</button>
      <button onClick={() => dispatch({type:'changePerson', payload:{name:'周', age:22} })}>改变用户</button>

    </div>
  )
}
